<?php

namespace app\modules\device\service;

use app\common\base\CommonService;
use app\helpers\DatetimeHelper;
use app\modules\device\models\Device;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Iot\V20180120\Models\QueryDeviceOriginalPropertyStatusRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Iot\V20180120\Models\SetDevicePropertyRequest;

class DeviceService extends CommonService
{
    function __construct()
    {
        // 对父类service(component)初始化，并指定model
        parent::init();
        $this->model = new Device();
    }

    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "iot.cn-shanghai.aliyuncs.com";
        return new Iot($config);
    }
    /**
     * 设备绑定
     */
    public function bindDevice($ownerId, $deviceName)
    {
        // 查找数据库中用户信息
        $info = $this->info([
            'condition' => [
                'ownerId' => $ownerId,
                'deviceName' => $deviceName,
            ]
        ]);

        if (!empty($info)) {
            return parent::error('ERROR_DEVICE_BOUND', '用户已注册设备');
        }

        $this->model->deviceName = $deviceName;
        $this->model->ownerId = $ownerId;
        $this->model->bind_timestamp = DatetimeHelper::msectime();
        $this->model->update_timestamp = DatetimeHelper::msectime();
        $this->model->save();

        return [
            'success' => 1,
        ];
    }

    /**
     * 设备解绑
     */
    public function unbindDevice($ownerId, $deviceName)
    {
        // 查找数据库中用户信息
        $info = $this->info([
            'condition' => [
                'ownerId' => $ownerId,
                'deviceName' => $deviceName,
            ]
        ]);

        if (empty($info)) {
            return parent::error('ERROR_NO_SUCH_DEVICE', '设备不存在');
        }

        $this->delete([
            'ownerId' => $ownerId,
            'deviceName' => $deviceName,
        ]);

        return [
            'success' => 1,
        ];
    }

    /**
     * 查询数据状态
     */
    public function querydeviceoriginalpropertystatus($asc,$pageSize,$productKey,$deviceName)
    {
        $client = self::createClient("accessKeyId", "accessKeySecret");//备注，此处需写入accessKeyId和accessKeySecret的值
        $queryDeviceOriginalPropertyStatusRequest = new QueryDeviceOriginalPropertyStatusRequest([
            "pageSize" => $pageSize,
            "productKey" => $productKey,
            "deviceName" => $deviceName,
            "asc" => $asc,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response = $client->queryDeviceOriginalPropertyStatusWithOptions($queryDeviceOriginalPropertyStatusRequest, $runtime);
            return [
                'response'=>$response,
            ];
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return [
                'response'=> $error->message
            ];
            }
       
    }

    /**
     * 设置开关状态
     */
    public function setdeviceproperty($value,$productKey,$deviceName)
    {
        $item=array("PowerSwitch"=>$value);
        $item=json_encode($item);
        $client = self::createClient("accessKeyId", "accessKeySecret");//备注，此处需写入accessKeyId和accessKeySecret的值
        $setDevicePropertyRequest = new SetDevicePropertyRequest([
            "productKey" => $productKey,
            "deviceName" => $deviceName,
            "items" =>$item,   
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response = $client->setDevicePropertyWithOptions($setDevicePropertyRequest, $runtime);
            return [
                'response'=>$response,
            ];
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return [
                'response'=> $error->message
            ];
        }
    }

    /**
     * 数据转换接口：deviceId -> id
     */
    public function deviceNameToId($ownerId, $deviceName)
    {
        $info = $this->info([
            'condition' => [
                'ownerId' => $ownerId,
                'deviceName' => $deviceName,
            ]
        ]);

        if (empty($info)) {
            return parent::error('ERROR_NO_SUCH_DEVICE', '设备不存在');
        }
        return $info['id'];
    }
}
